<template>
  <div>
    <!-- <Steps :current="current" :items="items"></Steps> -->
    <Row :gutter="10">
      <Col :span="4">
        <div class="card-container scroll-container">
          <p>推送方式</p>
          <span>{{ pushInfo.pushType == '2' ? '设备推送' : '项目推送' }}</span>
          <p class="mt-2">配置编码ID</p>
          <span>{{ pushInfo.code }}</span>
          <p class="mt-2">推送说明</p>
          <span>{{ pushInfo.pushDesc }}</span>
          <p class="mt-2">协议版本号</p>
          <span>{{ pushInfo.protobufVersion }}</span>

          <div class="info-item">
            <p class="mt-2">设备类型/型号</p>
            <Tree
              :tree-data="pushInfo.modelAlwaysVOS"
              :field-names="fileNames"
            />
          </div>
          <p class="mt-2">配置说明</p>
          <span>{{ pushInfo.configExplain }}</span>
          <p class="mt-2">配置类别</p>
          <span>{{ pushInfo.configType }}</span>
        </div>
      </Col>
      <Col :span="20">
        <Device
          :row="pushInfo"
          :deviceData="deviceData"
          @pushData="updataData"
          v-show="current == 0"
        ></Device>
        <div v-show="current == 1">
          <div class="card-container">
            <Row>
              <Col :span="6">
                <p>项目总数</p>
                <span>{{ statistics.projectNum }}</span></Col
              >
              <Col :span="3">
                <p>已选设备总数</p>
                <span>{{ dataSource.length }}</span></Col
              >
              <Col :span="3" v-for="(item, index) in statistics.typeList">
                <p>{{ item.typeName }}</p>
                <span>{{ item.sum }}</span>
              </Col>
            </Row>
          </div>
          <Row justify="space-between" class="mt-2">
            <Col>
              <div class="table-title">升级计划列表</div>
            </Col>
            <Col>
              <Space>
                <b-button v-if="!multiple" icon="delete" @click="onClear()"
                  >移除设备</b-button
                >
              </Space>
            </Col>
          </Row>
          <Table
            row-key="deviceCode"
            class="device_table"
            :scroll="{ x: 500, y: scrollHeight }"
            :columns="columnsDevice"
            size="middle"
            :data-source="dataSource"
            :row-selection="rowSelection"
          >
          </Table>
        </div>
      </Col>
    </Row>
    <!-- <div class="h-[1vh]"></div> -->
    <Flex justify="end" class="mt-2 steps-action">
      <Space>
        <b-button v-if="current < steps.length - 1" type="primary" @click="next"
          >下一步</b-button
        >
        <b-button v-if="current > 0" style="margin-left: 8px" @click="prev"
          >上一步</b-button
        >
        <b-button
          v-if="current == steps.length - 1"
          type="primary"
          @click="submitPush"
        >
          确认推送
        </b-button>
      </Space>
    </Flex>
  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref, watch } from 'vue';
import {
  Col,
  Flex,
  Modal,
  Row,
  Space,
  Steps,
  Table,
  type TableProps,
  Tree,
  TreeProps,
  message,
} from 'ant-design-vue';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { columnWidth, listToEnum } from '@/utils/utils';
import { appUpdateTypeEnum } from '@/constant/push';
import { fetchDictsOfType } from '@/api/dict';
import {
  configPushLog,
  configPushTotalLog,
  getDeviceMode,
  getModelStatistics,
} from '@/api/push';
import Device from './Device.vue';

const scrollHeight = ref(0);
onMounted(() => {
  const dom = document.querySelector('.device_table');
  scrollHeight.value = dom?.getBoundingClientRect().height - 40 || 0;
});

const fileNames: TreeProps['fieldNames'] = {
  title: 'typeName',
  children: 'modeName',
};

const props = defineProps({
  push: {
    type: Object,
    default: {},
  },
});
const pushInfo = ref<any>({});
watch(
  () => props.push,
  (newVal) => {
    console.log(newVal);
    pushInfo.value = newVal;
    pushInfo.value.title = '推送';
    // deviceData.value = newVal.sendDeviceVo;
    pushInfo.value.typeVOS = newVal.modelAlwaysVOS.map((item: any) => {
      return { id: item.modelTypeId, name: item.typeName };
    });
    if (newVal.modelAlwaysVOS) {
      newVal.modelAlwaysVOS.forEach((model) => {
        model.typeName = `${model.typeName}(${model.modeName.length})`;
        model.modeName = model.modeName.map((name) => {
          return {
            typeName: name,
          };
        });
      });
    }
  },
);

const modalList = ref<any[]>([]);
const sysDeviceModeEnum = ref<Record<string, any>>({});
onMounted(() => {
  fetchDictsOfType(['sys_device_mode']).then((res: any) => {
    const { sys_device_mode } = res.data;
    sysDeviceModeEnum.value = listToEnum(
      sys_device_mode,
      'dictValue',
      'dictLabel',
    );
  });
  getDeviceMode({}).then((res) => {
    modalList.value = res.data as any;
  });
});
const formatModal = (val: any) => {
  let arr = modalList.value.filter((item) => {
    return item.modelId == val;
  });
  return arr[0]?.model;
};
const current = ref<number>(0);
const next = () => {
  if (dataSource.value.length == 0) {
    message.error('请选择设备加入推送列表');
    return;
  }
  current.value++;
};
const prev = () => {
  current.value--;
  deviceData.value = [];
  deviceData.value = JSON.parse(JSON.stringify(dataSource.value));
};
const steps = [
  {
    title: '选择设备',
  },
  {
    title: '确认推送',
  },
];

interface TableRecord {
  deviceCode: string;
  deviceId: string;
  [key: string]: any;
}
const items = steps.map((item) => ({ key: item.title, title: item.title }));

const dataSource = ref<any[]>([]);

const statistics = ref({
  projectNum: 0,
  typeList: [
    {
      typeName: '预警终端',
      sum: 0,
    },
    {
      typeName: '预警喇叭',
      sum: 0,
    },
    {
      typeName: '桌面终端',
      sum: 0,
    },
  ],
});

const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    selectedRowKeys: selectedRow.value.map((row) => row.deviceCode), // Extract deviceCode for selectedRowKeys
    onChange: (
      selectedRowKeys: (string | number)[],
      selectedRows: TableRecord[],
    ) => {
      handlePushSelection(selectedRowKeys as string[], selectedRows);
    },
    getCheckboxProps: (record: TableRecord) => ({
      deviceCode: record.deviceCode,
      disabled: false,
    }),
  };
});
const multiple = ref(true);
const selectedRow = ref<TableRecord[]>([]);
const handlePushSelection = (keys: string[], rows: TableRecord[]) => {
  selectedRow.value = rows;
  multiple.value = !rows.length;
};
const columnsDevice = computed<ProTableProps['columns']>(() => [
  {
    title: '所属项目',
    dataIndex: 'projectName',
    align: 'center',
    width: columnWidth('projectName', dataSource.value, '所属项目'),
  },
  {
    title: '设备序列号',
    dataIndex: 'deviceCode',
    align: 'center',
    width: columnWidth('deviceCode', dataSource.value, '设备序列号'),
  },
  {
    title: '软件版本',
    dataIndex: 'version',
    align: 'center',
    customRender({ text, record }) {
      return text + (record.versionCode ? `(${record.versionCode})` : '');
    },
    width: columnWidth('version', dataSource.value, '所属项目', 20),
  },
  {
    title: '固件版本',
    dataIndex: 'firmwareVersion',
    align: 'center',
    width: columnWidth('firmwareVersion', dataSource.value, '所属项目'),
  },
  {
    title: '设备型号',
    dataIndex: 'model',
    align: 'center',
    // customRender({ text }) {
    //   return formatModal(text);
    // },
    width: columnWidth('model', dataSource.value, '所属项目', 20),
  },
  {
    title: '设备类型',
    dataIndex: 'deviceType',
    align: 'center',
    width: columnWidth('deviceType', dataSource.value, '所属项目'),
    customRender({ text }) {
      return sysDeviceModeEnum.value[text as string];
    },
  },
  {
    title: '地址',
    dataIndex: 'address',
    align: 'center',
    width: columnWidth('address', dataSource.value, '所属项目'),
  },
]);

const deviceData = ref<any[]>([]);

const getDeviceStatistics = (list: any) => {
  let _arr = list.map((item) => {
    return item.deviceId;
  });
  getModelStatistics(_arr.join(',')).then((res) => {
    console.log(res, 'res');
    statistics.value = res.data as any;
  });
};
const onClear = () => {
  for (let i = 0; i < selectedRow.value.length; i++) {
    for (let j = 0; j < dataSource.value.length; j++) {
      if (
        selectedRow.value[i].deviceCode === dataSource.value[j].deviceCode &&
        selectedRow.value[i].deviceId === dataSource.value[j].deviceId
      ) {
        dataSource.value.splice(j, 1);
      }
    }
  }
  if (rowSelection.value && rowSelection.value.onChange) {
    rowSelection.value.onChange([], []);
  }
};
const updataData = (data: any) => {
  dataSource.value = data;
  getDeviceStatistics(dataSource.value);
};
const emit = defineEmits(['pushUpdate', 'pushEnd']);
const submitPush = () => {
  if (dataSource.value.length == 0) {
    message.error('请选择设备加入推送列表');
    return;
  }

  Modal.confirm({
    title: '系统提示',
    centered: true,
    content: `确认推送？`,
    onOk: async () => {
      const res = await configPushTotalLog({
        taskId: pushInfo.value.id,
      });
      if (res.code == 200) {
        let list = [];
        dataSource.value.forEach(async (ele) => {
          list.push({
            configId: pushInfo.value.configId,
            configPushTotalId: res.data,
            code: ele.deviceCode,
            deviceId: ele.deviceId,
          });
        });
        const res1 = await configPushLog({ list });
        // emit('pushUpdate', {
        //   configId: pushInfo.value.versionId,
        //   configPushTotalId: res.data,
        //   upgradeStatus: '',
        // });
        message.success('推送成功');
        emit('pushEnd');
      }
    },
  });
};
</script>
<style lang="scss" scoped>
.table-title {
  height: 36px;
  line-height: 36px;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
.scroll-container {
  height: 60vh;
  overflow-y: auto;
  p {
    position: relative;
    color: #fff;
    &::before {
      position: absolute;
      left: -8px;
      top: 50%;
      transform: translateY(-50%);
      content: '';
      width: 2px;
      height: 12px;
      background-color: #1890ff;
    }
  }
}
.steps-action {
  position: absolute;
  bottom: 2vh;
  right: 2vh;
}
:deep(.ant-table) {
  height: calc(65vh - 310px);
}
:deep(.ant-table-body) {
  height: calc(65vh - 350px);
}
:deep(.ant-tree) {
  background: none;
}
/* 自定义步骤条样式 */
/* :deep(.ant-steps-item-active .ant-steps-item-content) {
  border: 1px solid #1890ff;
  background-color: #1890ff !important;
}
:deep(.ant-steps-item-icon) {
  display: none;
}
:deep(.ant-steps-item-content) {
  width: 100%;
  text-align: center;
  border: 1px solid #fff;
  cursor: default;
}
:deep(.ant-steps-item-title::after) {
  content: none;
}
:deep(.ant-steps .ant-steps-item:last-child) {
  flex: 1;
} */
</style>
